package com.alogic.terminal.xscript;

import com.alogic.terminal.Resolver;
import com.alogic.terminal.Terminal;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 执行修改密码指令
 * @author yyduan
 * @since 1.6.9.9
 * @version 1.6.9.9 [20170829 duanyy] <br>
 * - 增加ssh改密码功能 <br>
 */
public class XChangePwd extends Segment {
	/**
	 * 父节点id
	 */
	protected String pid = "$xshell";

	protected String lineId = "$line";
	
	protected String $newPwd = "";

	protected String $oldPwd = "";
	
	public XChangePwd(String tag, Logiclet p) {
		super(tag, p);
	}
	
	@Override 
	public void configure(Properties p){
		super.configure(p);
		
		pid = PropertiesConstants.getString(p,"pid", pid , true);
		lineId = PropertiesConstants.getString(p,lineId,lineId,true);
		$newPwd =  PropertiesConstants.getRaw(p,"value", "");
		$oldPwd =  PropertiesConstants.getRaw(p,"old", "");
	}

	@Override
	protected void onExecute(final XsObject root,final XsObject current,final LogicletContext ctx,final ExecuteWatcher watcher){
		Terminal t = ctx.getObject(pid);
		if (t == null){
			throw new BaseException("core.e1001","It must be in a xshell context,check your together script.");
		}
		
		String newPwd = PropertiesConstants.transform(ctx,$newPwd,"");
		String oldPwd = PropertiesConstants.transform(ctx,$oldPwd,"");

		if (StringUtils.isEmpty(newPwd)){
			throw new BaseException("core.e1401","the new password is empty");
		}

		if (StringUtils.isEmpty(oldPwd)){
			throw new BaseException("core.e1401","the old password is empty");
		}

		final XChangePwd self = this;
		final boolean log2log = this.children.isEmpty();

		Resolver resolver = new Resolver() {
			@Override
			public Object resolveBegin(String cmd) {
				return cmd;
			}

			@Override
			public void resolveLine(Object cookies, String content) {
				if (log2log){
					log(content);
				}else {
					if (StringUtils.isNotEmpty(content)) {
						ctx.SetValue(lineId, content);
						self.onSuperExecute(root, current, ctx, watcher);
					}
				}
			}

			@Override
			public void resolveEnd(Object cookies) {

			}
		};

		if (!t.changePassword(oldPwd,newPwd, resolver)){
			throw new BaseException("core.e1401","Failed to modify password");
		}
	}

	protected void onSuperExecute(XsObject root,XsObject current,
								  final LogicletContext ctx,final ExecuteWatcher watcher){
		super.onExecute(root,current,ctx,watcher);
	}
}